<template>
  <Page class="apply-form">
    <div class="questiion_head">
      <div class="head_title"><img src="~img/cydnQt/title.png" /></div>
      <div class="head_sub_tip">参与问卷小调查，为您提供更优质的服务!</div>
      <div class="bg_box">
        <div class="flex">
          <div class="short">{{ info.shortName || "" }}</div>
          <div class="content">
            <div class="name">{{ info.corpName }}</div>
            <div class="code">统一信用代码：{{ info.corpCredit }}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="content_box">
      <div class="question">
        <!-- 问卷内容 -->
        <div v-for="item in form.titleItems" :key="item.id">
          <div v-for="(items, index) in item.questionItems" :key="index">
            <questionOne
              :qType="items.questionType"
              :question="items"
              :answer="answer.answerItems[items.itemOrder - 1]"
              :index="index"
            ></questionOne>
          </div>
        </div>
        <div class="submit-btn">
          <van-button
            class="submit-bo"
            :loading="loading"
            @click="goSub"
            >提交</van-button
          >
        </div>
      </div>
    </div>
  </Page>
</template>
  
  <script>
import {
  paperList,
  token_cydn,
  questionsIds,
  questionsSee,
  questionsAnswer,
  answerSubmit,
  saveSubmitManager,
} from "@/interfaces/cydnQt";
import questionOne from "./components/questionOne.vue";

export default {
  name: "qtA",
  components: { questionOne },
  data() {
    return {
      dataList: {},
      form: {},
      answer: {
        answerId: "",
        questionId: null,
        doTime: 0,
        answerItems: [],
      },
      answer1: '',
      info: {
        shortName: "",
      },
      isWrite: true,
      loading: false,
    };
  },
  created() {
    this.tokenCydn();
    
  },
  methods: {
    async tokenCydn() {
      let param = {
        username: this.getUrlParam("phone"),
        platform: "miniApp",
      };
      const res = await token_cydn(param);
      if (res.code == 200) {
        // 更新state中的token_cydn
        this.$store.commit("user/setState", {
          attr: "token_cydn",
          data: res.token,
        });
        this.getIds();
      }
    },
    async getIds() {
      const params = {
        //id:'9777711e-8949-42bc-a09a-eedc8a12bb50' //url带上的
        //id:'c29a63b4-f884-4e98-b502-ad3f621f8a1a'
        id: this.getUrlParam("id"),
      };
      const res = await questionsIds(params);
      if (res.code == 200) {
        this.info = res.data;
        this.getIsWrite();
      }
    },
    async getIsWrite() {
      if(this.getUrlParam('answerId')){
           this.isWrite = true;
          this.getAnswer(this.getUrlParam('answerId'));
      }
      else{
          this.isWrite = false;
          this.getDetails();
      }
    },
    async getDetails(type) {
      const params = {
        id: this.info.interviewSurveyId,
      };
      const res = await paperList(params);
      if (res.code == 200) {
        if(type){
          this.dataList={
            ...this.dataList,
            id:res.data.id
          }
        }else{
          this.dataList = res.data;
          this.getTemplate();
        }
       
      }
    },
    async getAnswer(id) {
      const res = await questionsAnswer({ id: id });
      if (res.code == 200) {
        this.answer1 = res.data.answer;

        this.getDetails();
      }
    },
    getTemplate() {
      let answer = this.answer1;
      this.dataList.titleItems[0].questionItems.forEach((ele,index) => {
        if(this.isWrite){
          const cpList = JSON.parse(JSON.stringify(this.answer1.answerItems));
          const findOne = cpList.find((pre) => pre.questionId === ele.id);
          if (findOne) {
            findOne.contentArray = findOne.contentArray
              ? findOne.contentArray
              : [];
            findOne.itemOrder = index + 1;
            answer.answerItems[index] = findOne;
            answer.answerItems[index].qtype = ele.questionType;
            answer.answerItems[index].required = ele.required;
          } else {
            answer.answerItems[index] = {
              questionId: ele.id,
              content: null,
              contentArray: [],
              completed: false,
              itemOrder: index + 1,
              qtype: ele.questionType,
              required: ele.required,
            };
          }
          // this.answer = answer;
        }
        // 特殊处理填空题
        if (ele.questionType == "4") {
          let textCopy = ele.title.replace("<p>", "").replace("</p>", "").replace('<br/>', '');
          // console.log(textCopy, 'textCopytextCopy');
          let spanRegex = new RegExp(
            '<span class="gapfilling-span (.*?)">(.*?)<\\/span>',
            "g"
          );
          let formItemList = [];
          let gapfillingItems = textCopy.match(spanRegex);
          gapfillingItems.forEach((pre) => {
            textCopy = textCopy.replace(pre, "input");
          });
          textCopy.split("input").forEach((ped, index) => {
            formItemList.push({
              type: "text",
              content: ped,
            });
            if (index < textCopy.split("input").length - 1) {
              formItemList.push({
                type: "input",
                content: "",
                id: index,
              });
            }
          });
          ele.formItemList = formItemList;
        }
        this.form = this.dataList;
        this.answer.id = this.form.id;
      });
      if(this.answer1) {
        this.answer.answerItems = JSON.parse(JSON.stringify(this.answer1.answerItems))
      }
      //已填写，无需初始化答案
      if(!this.isWrite){
        this.initAnswer();
      }
    },
    initAnswer() {
      let titleItemArray = this.form.titleItems;
      for (let tIndex in titleItemArray) {
        let questionArray = titleItemArray[tIndex].questionItems;
        for (let qIndex in questionArray) {
          let question = questionArray[qIndex];
          this.answer.answerItems.push({
            questionId: question.id,
            content: null,
            contentArray: [],
            completed: false,
            itemOrder: question.itemOrder,
            required: question.required,
            qtype: question.questionType,
          });
        }
      }
    },
    goSub() {
      utils.ui.tips("提交成功");
      // 必填校验
      for (let i in this.answer.answerItems) {
        if (this.answer.answerItems[i].required == "1") {
          if (
            this.answer.answerItems[i].qtype == "2" ||
            this.answer.answerItems[i].qtype == "4"
          ) {
            if (this.answer.answerItems[i].contentArray.length == 0) {
              this.$toast("请填写带 * 的项");
              return;
            } else {
              const isValue = this.answer.answerItems[i].contentArray.some(
                (val) => val
              );
              if (!isValue) {
                this.$toast("请填写带 * 的项");
                return;
              }
            }
          } else {
            if (
              this.answer.answerItems[i].content == null ||
              this.answer.answerItems[i].content == ""
            ) {
              this.$toast("请填写带 * 的项");

              return;
            }
          }
        }
      }

      this.loading = true;
      answerSubmit(this.answer)
        .then((re) => {
          if (re.code === 200) {
            this.getSave(re.msg);
          } else {
            this.loading = false;
            // utils.ui.confirm(re.message);
          }
        })
        .catch((e) => {});
    },
    async getSave(id) {
      let params = {
        id: this.info.id,
        opType:'记录',
        corpName:this.info.corpName,
        corpCredit:this.info.corpCredit,
        interviewSurveyAnswerId: id,
      };
      const res = await saveSubmitManager(params);
      if (res.code == 200) {
        this.loading = false;
        utils.ui.tips("提交成功");
        this.getDetails(1);
      }
    },
    getUrlParam(name) {
      const queryStr = String(window.location).split("?")[1] || "";
      name = encodeURIComponent(name);
      let arr = new RegExp("(^|&)" + name + "=([^&]*)(&|$)").exec(queryStr);
      if (arr) {
        return decodeURIComponent(RegExp.$2);
      } else {
        return "";
      }
    },
  },
};
</script>
  
  <style lang="scss" scoped>
@import "@/assets/css/demo/index.scss";
.apply-form {
  position: relative;
  background-color: #f6f6f6;
}
.questiion_head {
  width: 100%;
  background-color: #e3eeff;
  position: relative;
  background-image: url("~img/cydnQt/bg.png");
  background-repeat: repeat-x;
  background-size: 100% auto;
  height: 260px;
  padding: 12px;
  .head_title {
    img {
      width: 130px;
    }
  }
  .head_sub_tip {
    font-size: 13px;
    margin-top: 6px;
  }
  .bg_box {
    background-image: url("~img/cydnQt/bg_small.png");
    width: 100%;
    height: 83px;
    background-repeat: repeat-x;
    background-size: 100% 100%;
    margin-top: 30px;
    display: flex;
    align-content: center;

    .flex {
      display: flex;
      align-items: center;
      margin-left: 20px;
      margin-right: 10px;
      // padding-left: 20px;
      // padding-top: 15px;
      .short {
        width: 40px;
        height: 40px;
        border-radius: 5px;
        background-color: #3282e4;
        font-size: 14px !important;
        font-family: Source Han Sans SC;
        color: #ffffff;
        text-align: center;
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        -webkit-box-pack: center;
        -ms-flex-pack: center;
        justify-content: center;
        -webkit-box-align: center;
        -ms-flex-align: center;
        align-items: center;
        line-height: 18px;
      }
      .content {
        margin-left: 8px;
        .name {
          color: #000;
        }
        .code {
          color: #5f6269;
          font-size: 12px;
        }
      }
    }
  }
}
.content_box {
  position: absolute;
  top: 192px;
  padding-bottom: 300px;
  overflow-y: auto;
  height: 100vh;
}
.question {
  width: 100vw;
  //   height: 100vh;
  //   background-color: #f6f6f6;
  // position: relative;
  // background-image: url("https://zx-1311146360.cos.ap-shanghai.myqcloud.com/wx_h5/wx_h5_top.png");
  // background-repeat: repeat-x;
  // background-size: 100% auto;
  padding: 13px;
}
.question-body-btn {
  margin: 40px;
  height: 79px;
  background: #4b91e7;
  border-radius: 3px;
  font-size: 16px;
  font-family: Alibaba PuHuiTi;
  font-weight: 400;
  color: #ffffff;
  display: flex;
  justify-content: center;
  align-items: center;
}
.question-title {
  height: 89px;
  // border: 1px solid red;
  .apply-top-title1 {
    margin: 40px 0 0 28px;
    font-size: 21px;
    font-family: Source Han Sans SC;
    font-weight: 500;
    color: #ffffff;
  }
  .apply-top-title2 {
    margin: 6px 0 0 28px;
    font-size: 17px;
    font-family: Source Han Sans SC;
    font-weight: 500;
    color: #ffffff;
  }
}

/* 问卷内容 */
.question-item {
  background: #ffffff;
  box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.06);
  border-radius: 9px;
  padding: 18px;
  margin-bottom: 16px;
  /* flex-wrap: wrap; */
}
.question-item-title {
  /* height: 50px; */
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  font-size: 15px;
  font-weight: 400;
  /* line-height: 59px; */
  color: #2c2c2c;
}
.question-ans {
  font-size: 14px;
  font-weight: 400;
  color: #777777 !important;
  /* display: flex;
      flex-direction: column;
      justify-content: space-between; */
  margin-top: 14px;
  display: flex;
  align-items: center !important;
  /* border: 1px solid red; */
  /deep/.van-radio__label {
    color: #777777 !important;
  }
}

/deep/.van-checkbox__label {
  color: #777777 !important;
}
.question-num {
  width: 68px;
  height: 24px;
  background: #ffffff;
  border: 1px solid #e0e1e5 !important;
  border-radius: 2px;
  margin: 0 8px;
  font-size: 13px;
  font-weight: 400;
  padding: 0 8px;
}
.question-item-title1 {
  font-size: 15px;
  font-weight: 400;
  color: #2c2c2c;
  /* display: flex;
      align-items: center; */
  /* flex-wrap: wrap; */
}
.question-num1 {
  width: 50px;
  height: 20px;
  background: #ffffff;
  border: 1px solid #e0e1e5 !important;
  border-radius: 2px;
  margin: 0 8px;
  margin-top: 6px;
  font-size: 13px;
  font-weight: 400;
  color: #777777;
  padding: 0 8px;
  display: inline-table;
}
.question-item-title2 {
  margin-top: 10px;
  font-size: 12px;
  font-family: Alibaba PuHuiTi;
  font-weight: 400;
  color: #777777;
}
.submit-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60px;
  //   background: #e3eeff;
  border-radius: 3px;
  font-size: 16px;
  font-family: Alibaba PuHuiTi;
  font-weight: 400;
  display: flex;
  justify-content: center;
  align-items: center;
}
.submit-bo {
  background: #356ded;
  height: 44px;
  width: calc(100% - 40px);
  color: #ffffff;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 20px;
}
.submit-bi {
  background: #999;
  height: 44px;
  width: calc(100% - 40px);
  color: #ffffff;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 20px;
}
input {
  -webkit-appearance: none;
}
textarea {
  margin-top: 10px;
  width: 100%;
  -webkit-appearance: none;
  border: 1px solid rgb(238, 232, 232);
  padding: 2px;
}
</style>
  